package com.synergy.stockflow.production.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.synergy.stockflow.model.Result;
import com.synergy.stockflow.production.create.MaterialRequisitionVo;
import com.synergy.stockflow.production.create.MrdOrMVo;
import com.synergy.stockflow.production.entity.MaterialRequisition;
import com.synergy.stockflow.production.entity.MaterialRequisitionDetail;
import com.synergy.stockflow.production.service.MaterialRequisitionDetailService;
import com.synergy.stockflow.production.service.MaterialRequisitionService;
import com.synergy.stockflow.warehouse.entity.InventoryTransaction;
import com.synergy.stockflow.warehouse.service.InventoryTransactionService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/material-requisition")
public class MaterialRequisitionController {
    @Autowired
    private MaterialRequisitionService materialRequisitionService;

    @Autowired
    private MaterialRequisitionDetailService materialRequisitionDetailService;

    @Autowired
    private InventoryTransactionService inventoryTransactionService;

    @GetMapping("/page")
    public Result getMaterialRequisition(
            @RequestParam(name = "current", defaultValue = "1") int current,
            @RequestParam(name = "size", defaultValue = "2") int size,
            @RequestParam(name = "requisitionCode", required = false) String requisitionCode,
            @RequestParam(name = "requisitionName", required = false) String requisitionName,
            @RequestParam(name = "requiredTime", required = false) String requiredTime,
            @RequestParam(name = "status", required = false) Integer status) {
        System.out.println(requiredTime+requisitionName+requisitionCode+status);
        Page<MaterialRequisitionVo> objectPage = new Page<>(current, size);
        List<MaterialRequisitionVo> materialRequisitionVos = materialRequisitionService.selectAll(objectPage,requisitionCode,requisitionName,requiredTime,status);
        objectPage.setRecords(materialRequisitionVos);
        return Result.success(objectPage);
    }

    @GetMapping("/selectByCode")
    public Result selectByCode(@RequestParam("requisition_code") String requisitionCode) {
        MaterialRequisitionVo materialRequisitionVo = materialRequisitionService.selectByCode(requisitionCode);
        return Result.success(materialRequisitionVo);
    }

    @GetMapping("/getMaterialByCode")
    public Result selectMByCode(@RequestParam("requisitionCode") String requisitionCode) {
        List<MrdOrMVo> mrdOrMVoList = materialRequisitionDetailService.selectByCode(requisitionCode);
        return Result.success(mrdOrMVoList);
    }

    @PutMapping("/update")
    public Result updateMaterialRequisitionDetails(@RequestBody MaterialRequisition materialRequisition) {
        materialRequisitionService.updateById(materialRequisition);
        QueryWrapper<MaterialRequisitionDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(MaterialRequisitionDetail::getRequisitionId, materialRequisition.getRequisitionId());
        materialRequisitionDetailService.remove(queryWrapper);

        materialRequisitionDetailService.saveBatch(materialRequisition.getMaterialRequisitionDetails());
        return Result.success(materialRequisition);
    }

    @DeleteMapping("/updateByStatus")
    public Result updateByStatus(@RequestParam("requisitionId") String requisitionId) {
        String one = materialRequisitionService.getOne(new QueryWrapper<MaterialRequisition>().lambda().eq(MaterialRequisition::getRequisitionId, requisitionId)).getRequisitionId();
        materialRequisitionDetailService.deleteByRequisitionId(one);
       return Result.success(materialRequisitionService.removeById(requisitionId));

    }

    //批量删除
    @PutMapping("/batchDelete")
    public Result delete(@RequestBody List<MaterialRequisition> requisitionId) {
        for (MaterialRequisition q : requisitionId) {
            materialRequisitionService.removeById(q.getRequisitionId());
            String one = materialRequisitionService.getOne(new QueryWrapper<MaterialRequisition>().lambda().eq(MaterialRequisition::getRequisitionId, requisitionId)).getRequisitionId();
            materialRequisitionDetailService.deleteByRequisitionId(one);
        }
        return Result.success(requisitionId);
    }


    //添加
    @PostMapping("/add")
    public Result add(@RequestBody MaterialRequisition materialRequisition) {
        materialRequisition.setRequisitionCode(generateRequisitionCode());
        materialRequisition.setStatus(0);
        materialRequisition.setCreateTime(new Date());
        materialRequisition.setUpdateTime(new Date());
        materialRequisitionService.save(materialRequisition);
        materialRequisition.getMaterialRequisitionDetails().forEach(item -> {
            item.setStatus(0);
            item.setCreateTime(new Date());
            item.setUpdateTime(new Date());
            item.setRequisitionId(materialRequisition.getRequisitionId());
            if(item.getActualQuantity().doubleValue()!=0.00){
                materialRequisitionDetailService.save(item);
            }
        });
        return Result.success(materialRequisition);
    }

    //生成领料编号
    private String generateRequisitionCode() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        String dateStr = sdf.format(new Date());

        // 查询当月的计划数量
        int count = materialRequisitionService.countCurrentMonthPlans();

        return "LL-" + dateStr + String.format("%03d", count + 1);
    }

    //添加详情表
    @PostMapping("/addDetail/{id}")
    public Result addDetail(@PathVariable("id") String requisitionId,
                            @RequestBody List<MaterialRequisitionDetail> materialRequisitionDetail) {
//        materialRequisitionDetail.setStatus(0);
//        materialRequisitionDetail.setCreateTime(new Date());
//        materialRequisitionDetail.setUpdateTime(new Date());
        materialRequisitionDetailService.saveBatch(materialRequisitionDetail);
        return Result.success(materialRequisitionDetail);
    }


    @PostMapping("/execute")
    public Result execute(@RequestBody MaterialRequisition materialRequisition) {
        List<InventoryTransaction> inventoryTransactions = new ArrayList<>();
        //  遍历领料单明细
        for (MaterialRequisitionDetail detail : materialRequisition.getMaterialRequisitionDetails()) {
            InventoryTransaction transaction = new InventoryTransaction();
            transaction.setTransactionType("MR_OUT");
            transaction.setSourceDocId(materialRequisition.getRequisitionId());
            transaction.setSourceDocType("material_requisition");
            transaction.setWarehouseId(detail.getWarehouseId());
            transaction.setMaterialId(detail.getMaterialId());
            transaction.setOperatorId(materialRequisition.getApplicantId());
            transaction.setBatchNo(detail.getDetailId());
            transaction.setQuantity(detail.getActualQuantity().negate());
            transaction.setTransactionTime(new Date());
            transaction.setRemarks("领料出库：" + materialRequisition.getRequisitionName());
            inventoryTransactions.add(transaction);
        }
        boolean saveResult = inventoryTransactionService.saveBatch(inventoryTransactions);

        if (saveResult) {
            // 更新领料单状态为已执行
            MaterialRequisition updateRequisition = new MaterialRequisition();
            updateRequisition.setRequisitionId(materialRequisition.getRequisitionId());
            updateRequisition.setStatus(1); // 设置为已领料状态
            updateRequisition.setUpdateTime(new Date()); // 设置实际领料时间
            materialRequisitionService.updateById(updateRequisition);

            return Result.success("领料执行成功");
        } else {
            return Result.error(400,"领料执行失败");
        }
    }

}
